<template>
  <div class="words-management">
    <div class="page-header">
      <h2 class="page-title">单词管理</h2>
      <div class="page-actions">
        <button class="btn primary" @click="showAddModal = true">
          <PlusIcon size="16" />
          添加单词
        </button>
        <div class="search-box">
          <input type="text" placeholder="搜索单词..." v-model="searchQuery" @input="handleSearch" />
          <SearchIcon size="16" />
        </div>
      </div>
    </div>

    <!-- <div class="filters">
      <div class="filter-group">
        <label>分类:</label>
        <select v-model="selectedCategory" @change="filterWords">
          <option value="">全部</option>
          <option v-for="category in categories" :value="category.id" :key="category.id">
            {{ category.name }}
          </option>
        </select>
      </div>

      <div class="filter-group">
        <label>难度:</label>
        <select v-model="selectedLevel" @change="filterWords">
          <option value="">全部</option>
          <option value="1">初级</option>
          <option value="2">中级</option>
          <option value="3">高级</option>
        </select>
      </div>

      <div class="filter-group">
        <label>排序:</label>
        <select v-model="sortBy" @change="filterWords">
          <option value="createdAt">添加时间</option>
          <option value="word">单词字母</option>
          <option value="views">浏览次数</option>
        </select>
      </div>
    </div> -->

    <div class="words-table">
      <table>
        <thead>
          <tr>
            <th>单词</th>
            <th>音标</th>
            <th>释义</th>
            <!-- <th>分类</th> -->
            <!-- <th>难度</th>
            <th>状态</th> -->
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="word in paginatedWords" :key="word.id">
            <td>
              <strong>{{ word.word }}</strong>
              <span class="phonetic" v-if="word.phonetic">/{{ word.phonetic }}/</span>
            </td>
            <td>{{ word.phonetic }}</td>
            <td>{{ word.definition }}</td>
            <!-- <td>
              <span class="category-tag" :style="{ backgroundColor: getCategoryColor(word.category) }">
                {{ getCategoryName(word.category) }}
              </span>
            </td> -->
            <!-- <td>
              <span class="level-badge" :class="`level-${word.level}`">
                {{ getLevelName(word.level) }}
              </span>
            </td> -->
            <!-- <td>
              <span class="status-badge" :class="{ active: word.status === 1 }">
                {{ word.status === 1 ? '已发布' : '未发布' }}
              </span>
            </td> -->
            <td>
              <button class="btn-icon" @click="showEditModalFlag(word)" title="编辑">
                <EditIcon size="16" />
              </button>
              <button class="btn-icon danger" @click="confirmDelete(word.id)" title="删除">
                <TrashIcon size="16" />
              </button>
            </td>
          </tr>
        </tbody>
      </table>

      <div class="pagination" v-if="filteredWords.length > itemsPerPage">
        <button @click="currentPage--" :disabled="currentPage === 1" class="pagination-btn">
          上一页
        </button>
        <span class="page-info">第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
        <button @click="currentPage++" :disabled="currentPage === totalPages" class="pagination-btn">
          下一页
        </button>
      </div>
    </div>
    <!-- 删除确认模态框 -->
    <div v-if="showDeleteModal" class="modal-overlay">
      <div class="confirm-modal">
        <div class="confirm-header">
          <h3>确认删除</h3>
        </div>
        <div class="confirm-body">
          <p>确定要删除吗？此操作无法撤销。</p>
        </div>
        <div class="confirm-footer">
          <button class="cancel-btn" @click="showDeleteModal = false">
            取消
          </button>
          <button class="confirm-btn" @click="deleteWord">确认删除</button>
        </div>
      </div>
    </div>
    <!-- 添加单词模态框 -->
    <div v-if="showAddModal" class="modal-overlay">
      <div class="word-modal">
        <div class="modal-header">
          <h3>添加新单词</h3>
          <button class="close-btn" @click="showAddModal = false">
            &times;
          </button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="handleAddWord">
            <div class="form-group">
              <label>单词</label>
              <input type="text" v-model="newWord.word" required placeholder="输入单词" />
            </div>

            <div class="form-group">
              <label>音标</label>
              <input type="text" v-model="newWord.phonetic" placeholder="输入音标" />
            </div>

            <div class="form-group">
              <label>释义</label>
              <textarea v-model="newWord.definition" required placeholder="输入单词释义"></textarea>
            </div>

            <div class="form-row">
              <!-- <div class="form-group">
                <label>分类</label>
                <select v-model="newWord.category">
                  <option
                    v-for="category in categories"
                    :value="category.id"
                    :key="category.id"
                  >
                    {{ category.name }}
                  </option>
                </select>
              </div>

              <div class="form-group">
                <label>难度</label>
                <select v-model="newWord.level">
                  <option value="1">初级</option>
                  <option value="2">中级</option>
                  <option value="3">高级</option>
                </select>
              </div> -->
            </div>

            <div class="form-actions">
              <button type="button" class="cancel-btn" @click="showAddModal = false">
                取消
              </button>
              <button type="submit" class="confirm-btn">保存</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 编辑用户模态框 -->
    <div v-if="showEditModal" class="modal-overlay">
      <div class="word-modal">
        <div class="modal-header">
          <h3>编辑单词</h3>
          <button class="close-btn" @click="showEditModal = false">
            &times;
          </button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="handleUpdateWord">
            <div class="form-group">
              <label>单词</label>
              <input type="text" v-model="editedWord.word" required placeholder="输入单词" />
            </div>

            <div class="form-group">
              <label>音标</label>
              <input type="text" v-model="editedWord.phonetic" placeholder="输入音标" />
            </div>

            <div class="form-group">
              <label>释义</label>
              <textarea v-model="editedWord.definition" required placeholder="输入单词释义"></textarea>
            </div>

            <div class="form-actions">
              <button type="button" class="cancel-btn" @click="showEditModal = false">
                取消
              </button>
              <button type="submit" class="confirm-btn">保存修改</button>
            </div>
          </form>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { PlusIcon, SearchIcon, EditIcon, TrashIcon } from "lucide-vue-next";
import {
  getWordsData,
  DeleteWordDataByWordIdApi,
  insertNewWordsApi,
  updateWordApi
} from "../../api/authService.js";
import WordModal from "../../components/WordModal.vue";
// import WordModal from '@/components/admin/WordModal.vue'
// import ConfirmModal from '@/components/admin/ConfirmModal.vue'

// 模拟数据
const words = ref([
  {
    id: 1,
    word: "abandon",
    phonetic: "əˈbændən",
    definition: "放弃，遗弃",
    category: 1,
    level: 2,
    status: 1,
    createdAt: "2023-05-10",
  },
]);

const categories = ref([
  { id: 1, name: "基础词汇", color: "#4361ee" },
  { id: 2, name: "商务英语", color: "#4895ef" },
  { id: 3, name: "科技词汇", color: "#3f37c9" },
]);

// 搜索和筛选
const searchQuery = ref("");
const selectedCategory = ref("");
const selectedLevel = ref("");
const sortBy = ref("createdAt");

const filteredWords = computed(() => {
  let result = [...words.value];

  // 搜索过滤
  if (searchQuery.value) {
    // console.log(searchQuery.value);
    const query = searchQuery.value.toLowerCase();

    result = result.filter(
      (word) =>
        // 确保 word.word 和 word.definition 都是有效的字符串
        (word.word &&
          typeof word.word === "string" &&
          word.word.toLowerCase().includes(query)) ||
        // 如果定义字段存在且是字符串，则根据定义进行过滤
        (word.definition &&
          typeof word.definition === "string" &&
          word.definition.toLowerCase().includes(query)) ||
        // 新增根据单词意思过滤的条件，定义字段作为单词意思
        (word.definition &&
          typeof word.definition === "string" &&
          word.definition.toLowerCase().includes(query))
    );
  }

  // 分类过滤
  if (selectedCategory.value) {
    result = result.filter((word) => word.category == selectedCategory.value);
  }

  // 难度过滤
  if (selectedLevel.value) {
    result = result.filter((word) => word.level == selectedLevel.value);
  }

  // 排序
  if (sortBy.value === "createdAt") {
    result.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
  } else if (sortBy.value === "word") {
    result.sort((a, b) => a.word.localeCompare(b.word));
  } else if (sortBy.value === "views") {
    result.sort((a, b) => (b.views || 0) - (a.views || 0));
  }

  return result;
});

// 分页
const currentPage = ref(1);
const itemsPerPage = 5;

const totalPages = computed(() =>
  Math.ceil(filteredWords.value.length / itemsPerPage)
);

const paginatedWords = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage;
  const end = start + itemsPerPage;
  return filteredWords.value.slice(start, end);
});

// 模态框状态
const showAddModal = ref(false);
// const showEditModal = ref(false);
const showDeleteModal = ref(false);
const currentWord = ref(null);
const wordToDelete = ref(null);

// 分类和难度辅助函数
const getCategoryName = (id) => {
  const category = categories.value.find((c) => c.id === id);
  return category ? category.name : "未知";
};

const getCategoryColor = (id) => {
  const category = categories.value.find((c) => c.id === id);
  return category ? category.color : "#ccc";
};

const getLevelName = (level) => {
  const levels = { 1: "初级", 2: "中级", 3: "高级" };
  return levels[level] || "未知";
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
};

// 过滤处理
const filterWords = () => {
  currentPage.value = 1;
};

// 单词操作
const editWord = (word) => {
  currentWord.value = { ...word };
  showEditModal.value = true;
};

const handleSaveWord = (wordData) => {
  if (wordData.id) {
    // 更新现有单词
    const index = words.value.findIndex((w) => w.id === wordData.id);
    if (index !== -1) {
      words.value[index] = wordData;
    }
  } else {
    // 添加新单词
    const newWord = {
      ...wordData,
      id: Math.max(...words.value.map((w) => w.id)) + 1,
      createdAt: new Date().toISOString().split("T")[0],
      status: 1,
    };
    words.value.unshift(newWord);
  }

  closeModal();
};

const closeModal = () => {
  showAddModal.value = false;
  showEditModal.value = false;
  currentWord.value = null;
};

const confirmDelete = (id) => {
  wordToDelete.value = id;
  showDeleteModal.value = true;
};

const DeleteWordDataByWordId = async (id) => {
  try {
    const response = await DeleteWordDataByWordIdApi(id);
    if (response) {
      console.log(response);
    } else {
      console.log("删除单词失败 error");
    }
  } catch (error) {
    console.log(error);
  }
};
const deleteWord = () => {
  // console.log();
  words.value = words.value.filter((word) => word.id !== wordToDelete.value);
  DeleteWordDataByWordId(wordToDelete.value);
  showDeleteModal.value = false;
  wordToDelete.value = null;
};

const loadGetWordArrayData = async () => {
  try {
    const res = await getWordsData();
    // console.log(res, '获取用户数据');
    if (res) {
      handWordArrayData(res.data);
      // console.log(res.data, '获取单词数据');
    } else {
      ElMessage.error(res.message || "获取单词列表失败");
    }
  } catch (error) {
    ElMessage.error("获取失败: ");
  } finally {
    // loading.value = false;
  }
};

const getRandomNumber = (min, max) => {
  return Math.floor(Math.random() * (max - min + 1)) + min;
};

const handWordArrayData = async (data) => {
  const transformedData = data.map((item) => ({
    id: item.id,
    word: item.word,
    phonetic: item.phonetic,
    definition: item.definition,
    category: getRandomNumber(1, 3),
    level: getRandomNumber(1, 3),
    status: getRandomNumber(1, 3),
    createdAt: "2025-04-07",
  }));
  // console.log(transformedData, '单词数据');
  words.value = transformedData;
};



// 添加新单词相关
const newWord = ref({
  word: '',
  phonetic: '',
  definition: '',
  category: 1,
  level: 1,
  status: 1
})

const editedWord = ref({
  word: '',
  phonetic: '',
  definition: ''
})



const showEditModal = ref(false)

const showEditModalFlag = (word) => {
  showEditModal.value = true
  console.log(word, '编辑单词');
  editedWord.value = word
}

const handleUpdateWord = async () => {
  // console.log(editedWord.value, '编辑单词');
  const wordToUpdate = {
    id: editedWord.value.id, // make sure the word has an ID
    word: editedWord.value.word,
    definition: editedWord.value.definition,
    phonetic: editedWord.value.phonetic
  };
  console.log(wordToUpdate, '编辑单词');
  try {
    const res = await updateWordApi(wordToUpdate); // You need to implement or import this API

    if (res.success) {
      // Update the word in the local list
      const index = words.value.findIndex(w => w.id === wordToUpdate.id);
      if (index !== -1) {
        words.value[index] = { ...wordToUpdate };
      }

      // Close modal and reset
      showEditModal.value = false;
      editedWord.value = {
        id: null,
        word: '',
        definition: '',
        phonetic: ''
      };
    } else {
      console.error('Update failed:', res.message);
      alert(res.message);
    }
  } catch (error) {
    console.error('Error updating word:', error);
    alert('Failed to update word');
  }
};





const handleAddWord = async () => {
  // 创建要提交的新单词对象
  const wordToAdd = {
    word: newWord.value.word,
    definition: newWord.value.definition,
    phonetic: newWord.value.phonetic
  };

  try {
    const res = await insertNewWordsApi(wordToAdd);

    if (res.success) {
      // 后端插入成功，再更新本地列表（可选）
      words.value.unshift({
        ...wordToAdd
      });

      // 重置表单
      resetNewWordForm();
      // 关闭模态框
      showAddModal.value = false;
      // 重置分页到第一页
      currentPage.value = 1;
    } else {
      console.error('插入失败:', res.message);
      alert(res.message);
    }
  } catch (error) {
    console.error('插入单词异常:', error);
    alert('插入单词失败');
  }
};

const resetNewWordForm = () => {
  newWord.value = {
    word: '',
    phonetic: '',
    definition: '',
    category: 1,
    level: 1,
    status: 1
  }
}


onMounted(() => {
  loadGetWordArrayData();
});
</script>

<style scoped>
.words-management {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 1rem;
}

.page-title {
  margin: 0;
  font-size: 1.5rem;
}

.page-actions {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s ease;
}

.btn.primary {
  background-color: var(--primary-color);
  color: white;
}

.btn.primary:hover {
  background-color: var(--primary-color);
  opacity: 0.9;
}

.search-box {
  position: relative;
  display: flex;
  align-items: center;
}

.search-box input {
  padding: 0.5rem 1rem 0.5rem 2rem;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  background-color: var(--card-bg);
  color: var(--text-color);
  width: 200px;
}

.search-box svg {
  position: absolute;
  left: 0.7rem;
  color: var(--text-secondary);
}

.filters {
  display: flex;
  gap: 1.5rem;
  flex-wrap: wrap;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.filter-group label {
  font-size: 0.9rem;
  color: var(--text-secondary);
}

.filter-group select {
  padding: 0.3rem 0.5rem;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  background-color: var(--card-bg);
  color: var(--text-color);
}

.words-table {
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
  background-color: var(--card-bg);
  box-shadow: var(--shadow);
  border-radius: 8px;
  overflow: hidden;
}

th,
td {
  padding: 1rem;
  text-align: left;
  border-bottom: 1px solid var(--border-color);
}

th {
  background-color: var(--hover-bg);
  font-weight: 600;
}

.phonetic {
  display: block;
  font-size: 0.8rem;
  color: var(--text-secondary);
  margin-top: 0.3rem;
}

.category-tag {
  display: inline-block;
  padding: 0.2rem 0.6rem;
  border-radius: 12px;
  font-size: 0.8rem;
  color: white;
}

.level-badge {
  display: inline-block;
  padding: 0.2rem 0.6rem;
  border-radius: 12px;
  font-size: 0.8rem;
  background-color: var(--hover-bg);
}

.level-badge.level-1 {
  background-color: rgba(40, 167, 69, 0.1);
  color: var(--success-color);
}

.level-badge.level-2 {
  background-color: rgba(255, 193, 7, 0.1);
  color: var(--warning-color);
}

.level-badge.level-3 {
  background-color: rgba(220, 53, 69, 0.1);
  color: var(--danger-color);
}

.status-badge {
  display: inline-block;
  padding: 0.2rem 0.6rem;
  border-radius: 12px;
  font-size: 0.8rem;
  background-color: var(--hover-bg);
}

.status-badge.active {
  background-color: rgba(40, 167, 69, 0.1);
  color: var(--success-color);
}

.btn-icon {
  background: none;
  border: none;
  cursor: pointer;
  padding: 0.3rem;
  border-radius: 4px;
  color: var(--text-secondary);
  margin-right: 0.5rem;
}

.btn-icon:hover {
  background-color: var(--hover-bg);
}

.btn-icon.danger:hover {
  color: var(--danger-color);
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1rem;
  margin-top: 1.5rem;
}

.pagination-btn {
  padding: 0.5rem 1rem;
  border: 1px solid var(--border-color);
  background-color: var(--card-bg);
  color: var(--text-color);
  border-radius: 4px;
  cursor: pointer;
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  font-size: 0.9rem;
  color: var(--text-secondary);
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .page-actions {
    width: 100%;
    justify-content: space-between;
  }

  .search-box input {
    width: 100%;
  }

  .filters {
    gap: 1rem;
  }
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: var(--card-bg);
  border-radius: 8px;
  width: 90%;
  max-width: 800px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: var(--shadow);
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid var(--secondary-color) !important;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h2 {
  margin: 0;
  font-size: 20px;
}

.close-btn {
  background: none;
  border: none;
  cursor: pointer;
  color: var(--secondary-color);
  padding: 5px;
}

.close-btn:hover {
  color: var(--text-color);
}

.modal-body {
  padding: 20px;
}

.confirm-modal {
  background-color: var(--card-bg);
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  box-shadow: var(--shadow);
}

.confirm-header {
  padding: 15px 20px;
  border-bottom: 1px solid var(--border-color);
}

.confirm-header h3 {
  margin: 0;
  font-size: 18px;
}

.confirm-body {
  padding: 20px;
}

.confirm-footer {
  padding: 15px 20px;
  border-top: 1px solid var(--border-color);
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn,
.confirm-btn {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  background-color: var(--secondary-color);
  color: white;
  border: none;
}

.confirm-btn {
  background-color: var(--danger-color);
  color: white;
  border: none;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.word-modal {
  background-color: var(--card-bg);
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.modal-header {
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
}

.form-group input,
.form-group textarea,
.form-group select {
  width: 90%;
  padding: 8px 5%;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group textarea {
  min-height: 80px;
  resize: vertical;
}

.form-row {
  display: flex;
  gap: 16px;
}

.form-row .form-group {
  flex: 1;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;

}

.form-actions>button {}

.cancel-btn {
  padding: 8px 16px;
  /* background-color: #f5f5f5; */
  background-color: var(--card-bg);
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.confirm-btn {
  padding: 8px 16px;
  background-color: #4361ee;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.confirm-btn:hover {
  background-color: #3a56d4;
}

input {
  background-color: var(--card-bg) !important;
  border: 1px solid var(--secondary-color) !important;
}

textarea {
  background-color: var(--card-bg) !important;
  border: 1px solid var(--secondary-color) !important;
}

select {
  background-color: var(--card-bg);
  color: var(--text-color);
  border: 1px solid var(--secondary-color) !important;
}

textarea {
  color: var(--text-color) !important;
}

input {
  color: var(--text-color) !important;
}
</style>